"""
订单成功页面
显示订单提交成功信息，提供评价入口和其他操作
"""

import tkinter as tk
from tkinter import ttk, messagebox
from ui.pages.scrollable_page import ScrollablePage
from core.models.order import Order, OrderStatus
from core.utils.logger import debug, info, warning, error
from core.utils.i18n import t
from datetime import datetime


class OrderSuccessPage(ScrollablePage):
    """订单成功页面"""
    
    def __init__(self, parent, controller):
        self.current_order = None
        super().__init__(parent, controller)
    
    def create_widgets(self):
        """创建页面组件"""
        debug("OrderSuccessPage: Creating widgets...")
        
        # 使用滚动框架
        content_frame = self.scrollable_frame
        
        # 创建各个区域
        self._create_thank_you_section(content_frame)
        self._create_order_info_section(content_frame)
        self._create_review_section(content_frame)
        self._create_action_buttons(content_frame)
        # 额外功能将在set_order时创建
    
    def set_order(self, order):
        """设置要显示的订单"""
        self.current_order = order
        if hasattr(self, 'order_info_frame'):
            self._update_order_display()
            self._update_recommendation_display()
        else:
            # 如果还没有创建额外功能，现在创建
            content_frame = self.scrollable_frame
            self._create_additional_features(content_frame)
            self._update_recommendation_display()
    
    def _create_thank_you_section(self, parent):
        """创建感谢信息区域"""
        # 主标题区域
        title_frame = ttk.Frame(parent, style='Welcome.TFrame')
        title_frame.pack(fill='x', pady=(20, 30))
        
        # 成功图标和标题
        success_label = ttk.Label(
            title_frame, 
            text=t('order_success.title_success'), 
            font=('Arial', 24, 'bold'),
            foreground='#27AE60',
            background='#ECF0F1'
        )
        success_label.pack(pady=(0, 10))
        
        # 感谢文字
        thank_label = ttk.Label(
            title_frame,
            text=t('order_success.thank_you'),
            font=('Arial', 16),
            foreground='#2C3E50',
            background='#ECF0F1'
        )
        thank_label.pack(pady=(0, 5))
        
        # 说明文字
        desc_label = ttk.Label(
            title_frame,
            text=t('order_success.description'),
            font=('Arial', 12),
            foreground='#7F8C8D',
            background='#ECF0F1'
        )
        desc_label.pack()
    
    def _create_order_info_section(self, parent):
        """创建订单信息区域"""
        # 订单信息框架
        self.order_info_frame = ttk.LabelFrame(parent, text=t('order_success.order_info_title'), padding=15)
        self.order_info_frame.pack(fill='x', pady=(0, 20))
        
        # 订单基本信息
        info_frame = ttk.Frame(self.order_info_frame)
        info_frame.pack(fill='x', pady=(0, 15))
        
        # 订单号
        order_id_frame = ttk.Frame(info_frame)
        order_id_frame.pack(fill='x', pady=3)
        ttk.Label(order_id_frame, text=t('order_success.order_id_label'), font=('Arial', 11, 'bold'), width=12).pack(side='left')
        self.order_id_label = ttk.Label(order_id_frame, text='', font=('Arial', 11))
        self.order_id_label.pack(side='left')
        
        # 下单时间
        time_frame = ttk.Frame(info_frame)
        time_frame.pack(fill='x', pady=3)
        ttk.Label(time_frame, text=t('order_success.order_time_label'), font=('Arial', 11, 'bold'), width=12).pack(side='left')
        self.time_label = ttk.Label(time_frame, text='', font=('Arial', 11))
        self.time_label.pack(side='left')
        
        # 订单状态
        status_frame = ttk.Frame(info_frame)
        status_frame.pack(fill='x', pady=3)
        ttk.Label(status_frame, text=t('order_success.order_status_label'), font=('Arial', 11, 'bold'), width=12).pack(side='left')
        self.status_label = ttk.Label(status_frame, text='', font=('Arial', 11, 'bold'))
        self.status_label.pack(side='left')
        
        # 订单金额
        amount_frame = ttk.Frame(info_frame)
        amount_frame.pack(fill='x', pady=3)
        ttk.Label(amount_frame, text=t('order_success.order_amount_label'), font=('Arial', 11, 'bold'), width=12).pack(side='left')
        self.amount_label = ttk.Label(amount_frame, text='', font=('Arial', 11, 'bold'), foreground='#E74C3C')
        self.amount_label.pack(side='left')
        
        # 分隔线
        ttk.Separator(info_frame, orient='horizontal').pack(fill='x', pady=10)
        
        # 商品清单
        ttk.Label(info_frame, text=t('order_success.items_list_label'), font=('Arial', 11, 'bold')).pack(anchor='w', pady=(0, 5))
        
        # 商品列表框架
        self.items_frame = ttk.Frame(info_frame)
        self.items_frame.pack(fill='x')
        
        # 总计
        total_frame = ttk.Frame(info_frame)
        total_frame.pack(fill='x', pady=(10, 0))
        ttk.Separator(total_frame, orient='horizontal').pack(fill='x', pady=(0, 10))
        
        total_info_frame = ttk.Frame(total_frame)
        total_info_frame.pack(fill='x')
        ttk.Label(total_info_frame, text=t('order_success.total_label'), font=('Arial', 12, 'bold')).pack(side='left')
        self.total_label = ttk.Label(total_info_frame, text='', font=('Arial', 14, 'bold'), foreground='#E74C3C')
        self.total_label.pack(side='right')
    
    def _create_review_section(self, parent):
        """创建评价区域"""
        review_frame = ttk.LabelFrame(parent, text=t('order_success.review_title'), padding=15)
        review_frame.pack(fill='x', pady=(0, 20))
        
        # 评价提示文字
        ttk.Label(
            review_frame,
            text=t('order_success.review_hint'),
            font=('Arial', 11),
            foreground='#7F8C8D'
        ).pack(pady=(0, 10))
        
        # 立即评价按钮
        self.review_btn = ttk.Button(
            review_frame,
            text=t('order_success.review_button'),
            command=self._open_review_dialog,
            style='Accent.TButton',
            width=20
        )
        self.review_btn.pack()
    
    def _create_action_buttons(self, parent):
        """创建操作按钮区域"""
        action_frame = ttk.LabelFrame(parent, text=t('order_success.other_actions'), padding=15)
        action_frame.pack(fill='x', pady=(0, 20))
        
        # 按钮网格
        button_grid = ttk.Frame(action_frame)
        button_grid.pack(fill='x')
        
        # 第一行按钮
        row1 = ttk.Frame(button_grid)
        row1.pack(fill='x', pady=(0, 10))
        
        ttk.Button(
            row1, 
            text=t('order_success.view_details'), 
            command=self._view_order_details,
            width=18
        ).pack(side='left', padx=(0, 10))
        
        ttk.Button(
            row1, 
            text=t('order_success.continue_shopping'), 
            command=self._continue_shopping,
            width=18
        ).pack(side='left', padx=(0, 10))
        
        # 第二行按钮
        row2 = ttk.Frame(button_grid)
        row2.pack(fill='x')
        
        ttk.Button(
            row2, 
            text=t('order_success.email_notification'), 
            command=self._send_email_notification,
            width=18
        ).pack(side='left', padx=(0, 10))
        
        ttk.Button(
            row2, 
            text=t('order_success.share_order'), 
            command=self._share_order,
            width=18
        ).pack(side='left')
    
    def _create_additional_features(self, parent):
        """创建额外功能区域"""
        # 推荐商品区域
        self._create_recommendation_section(parent)
        
        # 预计送达时间
        delivery_frame = ttk.LabelFrame(parent, text=t('order_success.delivery_info'), padding=15)
        delivery_frame.pack(fill='x', pady=(0, 20))
        
        # 预计送达时间
        delivery_time_frame = ttk.Frame(delivery_frame)
        delivery_time_frame.pack(fill='x', pady=(0, 5))
        ttk.Label(delivery_time_frame, text=t('order_success.delivery_time_label'), font=('Arial', 11, 'bold')).pack(side='left')
        self.delivery_time_label = ttk.Label(delivery_time_frame, text=t('order_success.delivery_time'), font=('Arial', 11), foreground='#27AE60')
        self.delivery_time_label.pack(side='left', padx=(10, 0))
        
        # 物流追踪提示
        ttk.Label(
            delivery_frame,
            text=t('order_success.tracking_hint'),
            font=('Arial', 10),
            foreground='#7F8C8D'
        ).pack(anchor='w')
        
        # 优惠券奖励（首次购买）
        if self._is_first_purchase():
            coupon_frame = ttk.LabelFrame(parent, text=t('order_success.reward_title'), padding=15)
            coupon_frame.pack(fill='x', pady=(0, 20))
            
            ttk.Label(
                coupon_frame,
                text=t('order_success.reward_congrats'),
                font=('Arial', 11, 'bold'),
                foreground='#E74C3C'
            ).pack(anchor='w', pady=(0, 5))
            
            ttk.Label(
                coupon_frame,
                text=t('order_success.reward_coupon1'),
                font=('Arial', 10),
                foreground='#27AE60'
            ).pack(anchor='w')
            
            ttk.Label(
                coupon_frame,
                text=t('order_success.reward_coupon2'),
                font=('Arial', 10),
                foreground='#27AE60'
            ).pack(anchor='w')
    
    def _update_order_display(self):
        """更新订单信息显示"""
        if not self.current_order:
            return
        
        order = self.current_order
        
        # 更新基本信息
        self.order_id_label.config(text=order.order_id)
        
        # 格式化时间
        try:
            dt = datetime.fromisoformat(order.created_at)
            time_str = dt.strftime('%Y-%m-%d %H:%M:%S')
        except:
            time_str = order.created_at
        self.time_label.config(text=time_str)
        
        # 更新状态
        status_text = order.get_status_display()
        status_color = order.get_status_color()
        self.status_label.config(text=status_text, foreground=status_color)
        
        # 更新金额
        self.amount_label.config(text=f'¥{order.total:.2f}')
        self.total_label.config(text=f'¥{order.total:.2f}')
        
        # 更新商品列表
        self._update_items_display()
    
    def _update_items_display(self):
        """更新商品列表显示"""
        # 清除现有商品
        for widget in self.items_frame.winfo_children():
            widget.destroy()
        
        if not self.current_order:
            return
        
        # 添加商品项
        for item in self.current_order.items:
            item_frame = ttk.Frame(self.items_frame)
            item_frame.pack(fill='x', pady=2)
            
            # 商品名称和数量
            name_label = ttk.Label(
                item_frame, 
                text=f'• {item.product_name} x{item.quantity}', 
                font=('Arial', 10)
            )
            name_label.pack(side='left')
            
            # 小计
            subtotal_label = ttk.Label(
                item_frame, 
                text=f'¥{item.subtotal:.2f}', 
                font=('Arial', 10, 'bold'),
                foreground='#27AE60'
            )
            subtotal_label.pack(side='right')
    
    def _is_first_purchase(self):
        """检查是否首次购买"""
        if not self.current_order or not self.controller.auth_service.is_logged_in():
            return False
        
        try:
            user_id = self.controller.auth_service.current_user.user_id
            user_orders = self.controller.order_service.get_user_orders(user_id)
            # 如果只有当前这一个订单，说明是首次购买
            return len(user_orders) <= 1
        except:
            return False
    
    def _open_review_dialog(self):
        """打开评价对话框"""
        if not self.current_order:
            messagebox.showwarning(t('common.tip'), t('order_success.order_unavailable'))
            return
        
        if not self.controller.auth_service.is_logged_in():
            messagebox.showwarning(t('order_success.login_required_title'), t('order_success.login_required_message'))
            return
        
        try:
            from ui.components.review_dialog import ReviewDialog
            
            # 为订单中的每个商品打开评价对话框
            for item in self.current_order.items:
                # 获取商品对象
                product = self.controller.product_service.get_product_by_id(item.product_id)
                if product:
                    # 打开评价对话框
                    ReviewDialog(
                        parent=self,
                        controller=self.controller,
                        product=product,
                        order=self.current_order
                    )
            
            # 注意：成功消息现在由评价对话框内部处理，这里不再显示
            # 用户完成评价后，对话框会自动显示成功消息并关闭
            
        except Exception as e:
            error(f"打开评价对话框失败: {e}")
            messagebox.showerror(t('order_success.review_failed_title'), t('order_success.review_failed_message', error=e))
    
    def _view_order_details(self):
        """查看订单详情"""
        if self.current_order:
            # 跳转到订单页面
            self.controller.show_page('OrdersPage')
        else:
            messagebox.showwarning(t('common.tip'), t('order_success.order_unavailable'))
    
    def _continue_shopping(self):
        """继续购物"""
        self.controller.show_page('ProductPage')
    
    def _send_email_notification(self):
        """发送邮件通知"""
        messagebox.showinfo(t('order_success.email_notification'), t('order_success.email_sent'))
    
    def _share_order(self):
        """分享订单"""
        if self.current_order:
            order_number = t('order_success.order_number', order_id=self.current_order.order_id)
            order_total = t('order_success.order_total', total=self.current_order.total)
            share_text = f"Ali Bao Bao - {order_number}, {order_total}"
            messagebox.showinfo(t('order_success.share_title'), t('order_success.share_message', text=share_text))
        else:
            messagebox.showwarning(t('common.tip'), t('order_success.order_unavailable'))
    
    def update_data(self):
        """更新页面数据"""
        if self.current_order:
            self._update_order_display()
    
    def _create_recommendation_section(self, parent):
        """创建推荐商品区域"""
        # 推荐商品框架
        rec_frame = ttk.LabelFrame(parent, text=t('order_success.recommend_title'), padding=15)
        rec_frame.pack(fill='x', pady=(0, 20))
        
        # 提示文字
        ttk.Label(
            rec_frame,
            text=t('order_success.recommend_hint'),
            font=('Arial', 10),
            foreground='#7F8C8D'
        ).pack(anchor='w', pady=(0, 10))
        
        # 推荐商品容器（横向布局）
        self.recommendation_container = ttk.Frame(rec_frame)
        self.recommendation_container.pack(fill='x')
    
    def _update_recommendation_display(self):
        """更新推荐商品显示"""
        if not self.current_order or not hasattr(self, 'recommendation_container'):
            return
        
        # 清除现有的推荐商品
        for widget in self.recommendation_container.winfo_children():
            widget.destroy()
        
        # 获取推荐商品
        try:
            recommended_products = self.controller.recommendation_service.recommend_for_order(
                self.current_order, 
                limit=3
            )
            
            if not recommended_products:
                # 如果没有推荐商品，显示提示
                ttk.Label(
                    self.recommendation_container,
                    text=t('order_success.no_recommendations'),
                    font=('Arial', 10),
                    foreground='#7F8C8D'
                ).pack()
                return
            
            # 创建商品卡片
            for product in recommended_products:
                self._create_product_card(self.recommendation_container, product)
                
        except Exception as e:
            error(f"更新推荐商品显示失败: {e}")
    
    def _create_product_card(self, parent, product):
        """创建商品卡片"""
        # 卡片主框架
        card_frame = ttk.Frame(parent, relief='raised', borderwidth=1)
        card_frame.pack(side='left', padx=10, pady=5, fill='both', expand=True)
        
        # 商品图片区域
        img_frame = ttk.Frame(card_frame, height=150)
        img_frame.pack(fill='both', expand=True, pady=(5, 0))
        
        # 显示图片（如果有）
        if hasattr(product, 'image_path') and product.image_path:
            try:
                from PIL import Image, ImageTk
                img = Image.open(product.image_path)
                img = img.resize((120, 120), Image.LANCZOS)
                photo = ImageTk.PhotoImage(img)
                img_label = ttk.Label(img_frame, image=photo)
                img_label.image = photo  # 保持引用
                img_label.pack(pady=15)
            except:
                # 如果图片加载失败，显示文字
                ttk.Label(img_frame, text='📦', font=('Arial', 40)).pack(pady=15)
        else:
            # 没有图片时显示图标
            ttk.Label(img_frame, text='📦', font=('Arial', 40)).pack(pady=15)
        
        # 商品信息区域
        info_frame = ttk.Frame(card_frame)
        info_frame.pack(fill='x', padx=10, pady=(0, 5))
        
        # 商品名称（限制长度）
        product_name = product.name
        if len(product_name) > 20:
            product_name = product_name[:20] + '...'
        
        name_label = ttk.Label(
            info_frame,
            text=product_name,
            font=('Arial', 10),
            foreground='#2C3E50',
            anchor='center'
        )
        name_label.pack(pady=5)
        
        # 价格区域
        price_frame = ttk.Frame(info_frame)
        price_frame.pack(pady=5)
        
        # 显示折扣价或原价
        discounted_price = product.get_discounted_price()
        if discounted_price < product.price:
            ttk.Label(
                price_frame,
                text=f'¥{discounted_price:.2f}',
                font=('Arial', 12, 'bold'),
                foreground='#E74C3C'
            ).pack(side='left')
            ttk.Label(
                price_frame,
                text=f'¥{product.price:.2f}',
                font=('Arial', 9),
                foreground='#95A5A6',
                background='#ECF0F1'
            ).pack(side='left', padx=(5, 0))
        else:
            ttk.Label(
                price_frame,
                text=f'¥{product.price:.2f}',
                font=('Arial', 12, 'bold'),
                foreground='#E74C3C'
            ).pack()
        
        # 加入购物车按钮
        add_cart_btn = ttk.Button(
            card_frame,
            text=t('order_success.add_to_cart'),
            command=lambda p=product: self._add_to_cart_from_recommendation(p),
            width=15
        )
        add_cart_btn.pack(pady=(5, 10))
    
    def _add_to_cart_from_recommendation(self, product):
        """从推荐区域添加商品到购物车"""
        try:
            # 添加商品到购物车
            self.controller.shopping_cart.add_item(product, quantity=1)
            
            # 显示成功提示
            messagebox.showinfo('成功', f'{product.name} 已添加到购物车')
            
            # 更新购物车显示（如果产品页面存在）
            try:
                if 'ProductPage' in self.controller.pages:
                    product_page = self.controller.pages['ProductPage']
                    if hasattr(product_page, 'update_cart_display'):
                        product_page.update_cart_display()
            except:
                pass
                
        except Exception as e:
            error(f"添加商品到购物车失败: {e}")
            messagebox.showerror('错误', f'添加到购物车失败: {e}')
